package com.laikan.reader.database.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wx
 * @version 创建时间：2015-12-14 上午10:47:09
 * @E-mail wx1343571153@163.com
 * @userId 用户ID
 * @data 存储数据
 * @dataType 数据类型
 * @category
 */

public class DAO {

    private DbHelper helper;
    //    private SQLiteDatabase db;
    private Context context;
    /**
     * 当前存储类型
     */
    private String currDataType = "0";
    /**
     * 单个任务数量
     */
    private int TaskCount = 30;

    public DAO(Context context) {
        // 得到一个helper
        this.context = context;
        helper = new DbHelper(context);

    }

    /**
     * 分发任务 同步服务
     */
    public void distributionTask() {
        if (IsHaveData()) {
            // 所有数据集合
            List<BookRecord> ls = new ArrayList<BookRecord>();
            // 单个任务集合
            List<BookRecord> taskLs = new ArrayList<BookRecord>();
            ls = query();
            if (ls.size() <= TaskCount) {
                ThreadPool.Instance().addTask(new HistoryTask(query(), context, this));
            }else {

                for (int i = 0; i < ls.size(); i++) {
                    taskLs.add(ls.get(i));
                    if (i > 0 && i % TaskCount == 0) {
                        ThreadPool.Instance().addTask(new HistoryTask(query(), context, this));
                        taskLs = new ArrayList<BookRecord>();
                    }

                }
            }
        }
    }

    /**
     * 登录情况下 插入数据 判断是否已有
     *
     * @param data
     * @param userid
     */
    public void insertDataAndUserId(String userid, String data) {
        // 通过helper得到一个数据库
        if (IsDataSimpleAndUserId(userid, data)) {
            SQLiteDatabase db = helper.getReadableDatabase();

            ContentValues values = new ContentValues();
            values.put("userId", userid);
            values.put("data", data);
            values.put("dataType", currDataType);
            db.insert("record", null, values);
            closeDB(db, null);
        }

    }

    /**
     * 离线模式还有未登录情况下 插入数据 判断是否已有
     *
     * @param data
     */
    public void insertData(String data) {
        // 通过helper得到一个数据库
        if (IsDataSimple(data)) {
            SQLiteDatabase db = helper.getReadableDatabase();
            ContentValues values = new ContentValues();
            values.put("userId", "0");
            values.put("data", data);
            values.put("dataType", currDataType);
            db.insert("record", null, values);
            closeDB(db, null);
        }

    }

    /**
     * 删除数据
     *
     * @param data
     */
    public void delete(String userid, String data) {
        SQLiteDatabase db = helper.getWritableDatabase();
        String[] s = {userid, data, currDataType};
        db.delete("record", "userId = ? and data = ? and dataType = ?", s);
        closeDB(db, null);
    }

    /**
     * 查询所有数据
     *
     * @return
     */
    public List<BookRecord> query() {
        List<BookRecord> list = new ArrayList<BookRecord>();
        SQLiteDatabase db = helper.getReadableDatabase();
        String[] s = {"userId", "data", "dataType"};
        Cursor cursor = db.query("record", s, null, null, null, null, null);
        while (cursor.moveToNext()) {
            BookRecord bookRecord = new BookRecord();
            bookRecord.setData(cursor.getString(cursor.getColumnIndex("data")));
            bookRecord.setUserId(cursor.getString(cursor.getColumnIndex("userId")));
            bookRecord.setDataType(cursor.getString(cursor.getColumnIndex("dataType")));
            list.add(bookRecord);
        }
        closeDB(db, cursor);
        return list;
    }

    /**
     * 查询数据是否为空
     *
     * @return
     */
    public boolean IsHaveData() {
        boolean isHave;
        SQLiteDatabase db = helper.getReadableDatabase();
        String[] s = {"userId", "data", "dataType"};
        Cursor cursor = db.query("record", s, null, null, null, null, null);
        isHave = (cursor.getCount() == 0);
        closeDB(db, cursor);
        return !isHave;
    }

    /**
     * 判断数据是否添加
     *
     * @return
     */
    public boolean IsDataSimpleAndUserId(String userid, String data) {
        SQLiteDatabase db = helper.getReadableDatabase();
        Cursor cursor = db.rawQuery("select * from record where userId=? and data = ? and dataType = ?", new String[]{userid, data, currDataType});
        boolean isDataSimple = false;
        if (!cursor.isClosed()){

            isDataSimple = (cursor.getCount() == 0);
        }
        closeDB(db, cursor);
        return isDataSimple;

    }

    /**
     * 判断数据是否添加
     *
     * @return
     */
    public boolean IsDataSimple(String data) {
        SQLiteDatabase db = helper.getReadableDatabase();
        Cursor cursor = db.rawQuery("select * from record where  data = ? and dataType = ?", new String[]{data, currDataType});

        boolean isDataSimple = false;
        if (!cursor.isClosed()){

            isDataSimple = (cursor.getCount() == 0);
        }
        closeDB(db, cursor);
        return isDataSimple;
    }

    public void update(String id, String success) {
        SQLiteDatabase db = helper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("success", success);
        String[] s = {id};
        db.update("stu", values, "id=?", s);
        closeDB(db, null);
    }

    /**
     * 登录情况下 插入数据 判断是否已有
     */
    public void insertFont(String id, String success) {
        // 通过helper得到一个数据库
        if (IsFontTypeInsert(id)) {
            SQLiteDatabase db = helper.getReadableDatabase();
            ContentValues values = new ContentValues();
            values.put("id", id);
            values.put("success", success);
            db.insert("recordfont", null, values);
            closeDB(db, null);
        }

    }

    /**
     * 判断数据是否添加
     *
     * @return
     */
    public boolean IsFontTypeInsert(String id) {
        boolean isFontType;
        SQLiteDatabase db = helper.getReadableDatabase();
        Cursor cursor = db.rawQuery("select * from recordfont where id =?", new String[]{id});
        isFontType = cursor.getCount() == 0;
        closeDB(db, cursor);
        return isFontType;
    }

    private void closeDB(SQLiteDatabase db, Cursor cursor) {
        if (cursor != null && !cursor.isClosed()) {
            cursor.close();
        }
        if (db != null) {
            db.close();
        }
    }
}
